﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Bzzb.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;

namespace Bzzb.Controllers
{
    public class RoleController : BaseController
    {
        private readonly ILogger<RoleController> _logger;
        public RoleController(ILogger<RoleController> logger, IFreeSql fsql) : base(fsql)
        {
            this._logger = logger;
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Index([FromForm] long id, [FromForm] int pageIndex = 1, [FromForm] int pageSize = 10)
        {
            List<Role> roles = await _fsql.Select<Role>().Count(out var total).Page(pageIndex, pageSize).ToListAsync();
            _logger.LogInformation(_fsql.Select<Role>().Page(pageIndex, pageSize).ToSql());

            JArray ja_role = new JArray();
            if (roles != null && roles.Count > 0) {
                foreach (Role role in roles)
                {
                    // 查询出来所有角色的用户
                    List<long> uids = await _fsql.Select<RoleUser>().Where(ru => ru.Rid == role.Id).ToListAsync(ru => ru.Uid);

                    JObject jo_role = JObject.FromObject(role);
                    if (uids != null && uids.Count > 0)
                    {
                        List<User> users = await _fsql.Select<User>().Where(u => uids.Contains(u.Id)).ToListAsync();
                        jo_role.Add("users", JArray.FromObject(users));
                    }
                    else {
                        jo_role.Add("users", new JArray());
                    }
                    ja_role.Add(jo_role);
                }
            }

            JObject data = new JObject();
            data.Add("total", total);
            data.Add("list", ja_role);
            return RenderJson(data: data);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Save([FromForm] Role role)
        {
            long id = await _fsql.Insert(role).ExecuteIdentityAsync();
            role.Id = id;

            return RenderJson(data: role);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Delete([FromForm] long id) {
            int affrows = -1;
            _fsql.Transaction(() => {
                // 删除角色和员工对应关系
                affrows = _fsql.Delete<RoleUser>().Where(ru => ru.Rid == id).ExecuteAffrows();
                // 删除角色和权限对应关系
                affrows = _fsql.Delete<RolePermission>().Where(rp => rp.Rid == id).ExecuteAffrows();

                affrows = _fsql.Delete<Role>().Where(r => r.Id == id).ExecuteAffrows();
            });
            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Update([FromForm] Role role) {
            int affrows = await _fsql.Update<Role>().SetSourceIgnore(role, colval => colval == null).ExecuteAffrowsAsync();
            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Show([FromForm] long id) {
            Role role = await _fsql.Select<Role>().Where(d => d.Id == id).ToOneAsync();
            return RenderJson(data: role);
        }
    }
}
